
from datetime import datetime, timedelta, timezone
from jose.exceptions import ExpiredSignatureError, JWTError
from jose import jwt
from typing import Optional
from fastapi import Header
from utils.logger import logger
from utils.response import HttpResponse
from exception.excepts import  UnAuthentication
from config import setting


def create_access_token(user_id: str,
                       username:str,
                       hour:Optional[int] = int(setting.JWT_EXPIRED))->HttpResponse:
    # 设置过期时间
    expire = datetime.now(timezone.utc) + timedelta(hours=hour)
    # exp 必传参数
    to_encode = {"exp": expire, "user_id": user_id, "username": username}
    # 生成token，algorithm使用 HS256 加密算法
    access_token = jwt.encode(to_encode, setting.JWT_SECRET_KEY, algorithm='HS256')
    return HttpResponse.success(data=access_token)

# 签名秘钥
def check_access_token(token: str=Header(...)):
    try:
        # 验证token
        payload = jwt.decode(token, setting.JWT_SECRET_KEY, algorithms=['HS256'])
        logger.info("access_token,验证信息:{}".format(payload))
        return payload
    except ExpiredSignatureError:
        logger.warning("access_token 已过期")
        raise UnAuthentication(detail="access_token 已过期")
    except JWTError:
        logger.error("access_token 验证失败")
        raise UnAuthentication(detail="access_token 验证失败")



